package com.tencent.qf.mybatis.filter;

import com.tencent.qf.common.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.context.ApplicationContext;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "dynamicProdDataSourceFilter", urlPatterns = {"/*"})
public class DynamicProdDataSourceFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String linkToProdDB = request.getHeader("linkToProdDB");

        ApplicationContext applicationContext = SpringContextUtils.getApplicationContext();
        String env = applicationContext.getEnvironment().getActiveProfiles()[0];
        if (StringUtils.isNotEmpty(linkToProdDB) && !"prod".equals(env)) {
            MDC.put("linkToProdDB", "prod");
            log.debug("filter success! set ThreadLocal key: linkToProdDB");
        }

        filterChain.doFilter(servletRequest, servletResponse);

        if (StringUtils.isNotEmpty(linkToProdDB) && !"prod".equals(env)) {
            MDC.remove("linkToProdDB");
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
